package cn.jhz.learn.community_dynamic.app.websocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import cn.jhz.learn.community_dynamic.manager.WebSocketManager;
import cn.jhz.learn.community_dynamic.model.UserEntity;

@Component
public class WebsocketHandler extends TextWebSocketHandler {
    // 保存所有的用户session
    private final WebSocketManager webSocketManager;
    
    @Autowired
    public WebsocketHandler(WebSocketManager webSocketManager) {
	super();
	this.webSocketManager = webSocketManager;
    }
    
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
	System.out.println("afterConnectionEstablished");
	this.webSocketManager.cacheInstance(String.valueOf(((UserEntity) session.getAttributes().get("user")).getLoginId()), session);
    }
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception{
	System.out.println("handleTransportError");
	exception.printStackTrace();
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception{
	System.out.println("afterConnectionClosed");
	this.webSocketManager.clearInstance(String.valueOf(((UserEntity) session.getAttributes().get("user")).getLoginId()));
    }
}
